package com.message.notify;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import android.webkit.CookieManager;
import android.webkit.SslErrorHandler;

import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RemoteViews;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import com.message.notify.utils.HttpUtility;
import com.message.notify.utils.SharedPreferencesManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;


public class MainActivity extends AppCompatActivity {
    WebView webView;
    String username = "";
    String password = "";
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:   //返回键的id
                this.finish();
                //调用后台退出接口
                webView.setWebViewClient(new WebViewClient() {
                    @Override
                    public boolean shouldOverrideUrlLoading(WebView view, String url) {
                        view.loadUrl(url, null);
                        return true;
                    }

                    @Override
                    public void onPageFinished(WebView webView, String s) {
                        super.onPageFinished(webView, s);
                        //安卓调用js方法。注意需要在 onPageFinished 回调里调用
                        webView.post(new Runnable() {
                            @Override
                            public void run() {
                                webView.loadUrl("javascript:outLogAndroid('"+username+"','"+password+"')");

                            }
                        });
                    }
                }) ;
                //返回login
                Intent intent = new Intent();

                intent.setClass(MainActivity.this, LoginAcitvity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //清除该activity之上的所有activity
                intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); //如果activity在任务栈中存在，则复用该实例，否则创建新的实例
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //创建新的任务栈
                startActivity(intent);
                return false;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = getIntent();//获取告警类型
        String notify = intent.getStringExtra("notify");
//        getSupportActionBar().hide();
        getSupportActionBar().setTitle("GNSS告警信息管理系统");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("iGMAS监测告警信息管理系统");



        SharedPreferencesManager instance = SharedPreferencesManager.getInstance(MainActivity.this);
        String token = instance.getSharedPreferences().getString("auth", null);
//        String username = instance.getSharedPreferences().getString("username", null);
//        String password = instance.getSharedPreferences().getString("password", null);
        username = intent.getStringExtra("username");
        password = intent.getStringExtra("password");

        //获得控件
        webView = (WebView) findViewById(R.id.wv_webview);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        //设置js可以直接打开窗口，如window.open()，默认为false
        webView.getSettings().setJavaScriptEnabled(true);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true); // 允许Cookie

        //是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        webView.getSettings().setSupportZoom(false);
        webView.getSettings().setDomStorageEnabled(true);
        //是否可以缩放，默认true
        webView.getSettings().setBuiltInZoomControls(false);
        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN); //支持内容重新布局

        // 是否显示缩放按钮，默认false
        webView.getSettings().setUseWideViewPort(true);
        // 设置此属性，可任意比例缩放。大视图模式
//        webView.getSettings().setLoadWithOverviewMode(true);

        //设定缩放控件隐藏
        webView.getSettings().setDisplayZoomControls(true);

        // 和setUseWideViewPort(true)一起解决网页自适应问题
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setAppCacheEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        if("warn".equals(notify)){
            webView.loadUrl("http://124.17.81.85:8080/GNSS/#/warn");
        }else if("examine".equals(notify)){
            webView.loadUrl("http://124.17.81.85:8080/GNSS/#/myExamineList");
        }else{
            webView.loadUrl("http://124.17.81.85:8080/GNSS/#/login");
        }



        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
//        webView.setWebViewClient(new WebViewClient(){
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                //使用WebView加载显示url
//                view.loadUrl(url);
//                //返回true
//                return true;
//            }
//        });


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
                super.onReceivedSslError(view, handler, error);
            }

            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                //安卓调用js方法。注意需要在 onPageFinished 回调里调用
                System.out.println("请求路径为："+s);

                if(s.indexOf("login")>0){
                    ProgressDialog dialog = ProgressDialog.show(MainActivity.this, "提示", "正在登陆中");
                    dialog.show();
                    webView.post(new Runnable() {
                        @Override
                        public void run() {

                            webView.loadUrl("javascript:loginAndroid('"+username+"','"+password+"')");
                            dialog.dismiss();//调用此方法可以取消对话框
//                        webView.evaluateJavascript("javascript:loginAndroid('admin','iGMAS123&tarc')", new ValueCallback<String>() {
//                            @Override
//                            public void onReceiveValue(String s) {
//                                Log.d("TAG", s);
//                            }
//                        });
                        }
                    });
                }

            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                webView.loadUrl("javascript:(function() { " +
                        "var element = document.getElementById('login-div');" +
                        "element.style.display = 'none';" +
                        "})()");
            }
        }) ;


//        webView.evaluateJavascript("javascript:loginAndroid('admin','iGMAS123&tarc')", new ValueCallback<String>() {
//            @Override
//            public void onReceiveValue(String s) {
//                //打印js方法返回值
//                System.out.println("js方法返回的结果： " +s);
//                Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
//            }
//        });

        //初始化auth
        initAuthorization(null,username,password);

        // 定时任务实现
        //initDelay();
        Intent intent2 = new Intent(this, NotificationReceiver.class);
        intent2.putExtra("token",token);
        intent2.putExtra("username",username);
        intent2.putExtra("password",password);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 1*1*1000, pendingIntent);

    }

    private void initDelay() {
        Handler handler = new Handler();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                //要执行的方法
                Log.d("TAG", "定时任务");
                getauth_warn(null);//获取告警
                getauth_examine(null);//获取审批
                //5分钟执行一次
//                handler.postDelayed(this, 5*60*1000);
                //一分钟执行一次
                handler.postDelayed(this, 1*60*1000);
            }
        };

        handler.postDelayed(runnable, 1000);
    }

    /**
     * toast消息提醒
     *
     * @param view
     */
    public void toastClick(View view) {
        Toast.makeText(this, "Toast消息提醒", Toast.LENGTH_SHORT).show();
    }

    /**
     * notification消息通知
     *
     * @param view
     */
    @SuppressLint("WrongConstant")
    public void notificationClick(View view) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        String channelId = "com.message.notify";
        String channelName = "notification";
        //判断api版本大于等于26
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, channelId);
        } else {
            builder = new NotificationCompat.Builder(this);
            builder.setChannelId(channelId);
        }
        builder.setContentTitle("告警通知")//设置消息通知标题
                .setContentText("您有2条告警，请查收")//设置消息通知内容
                .setWhen(System.currentTimeMillis())//设置消息通知发送时间
                .setSmallIcon(R.mipmap.app_icon)//设置小童通知状态栏图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.app_icon))//设置消息通知下拉图标
                .setPriority(NotificationCompat.PRIORITY_HIGH);//设置消息优先级-

        //设置消息通知点击意图
//        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.baidu.com"));
        Intent intent = new Intent(Intent.ACTION_VIEW);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);

        //点击消息通知后删除的两种实现方法
        //第一种
        builder.setAutoCancel(true);
        //第二种
        int notificationId = 1;
//        manager.cancel(notificationId);

        //设置消息通知的提醒效果
        builder.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luan.ogg")))//设置消息声音
                .setVibrate(new long[]{0, 1000, 1000, 1000})//设置消息震动，需要加入android.permission.VIBRATE权限
                .setLights(Color.GREEN, 1000, 1000)//设置消息提醒灯
                .setDefaults(NotificationCompat.DEFAULT_ALL);//设置默认效果

        //设置悬挂弹出
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        builder.setFullScreenIntent(pendingIntent, true);

        Notification notification = builder.build();
        manager.notify(notificationId, notification);
    }

    @SuppressLint("WrongConstant")
    public void notificationALarm_bak(JSONObject data1,int type) throws JSONException {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        String channelId = "com.message.notify";
        String channelName = "notification";
        //判断api版本大于等于26
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, channelId);
        } else {
            builder = new NotificationCompat.Builder(this);
            builder.setChannelId(channelId);
        }
        JSONArray data;
        StringBuffer sb = new StringBuffer();

        String title;
        String SummaryText;
        Intent intent = new Intent(this, MainActivity.class);

        if(type == 0){//告警
            if("0".equals(data1.getString("total"))){
                return;
            }
            data = data1.getJSONArray("list");
            sb.append("您有" + data1.get("total") + "条告警，请查收\n");
            SummaryText = "您有" + data1.get("total") + "条告警，请查收\n";
            intent.putExtra("notify","warn");
            title = "告警通知";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("" + new Date() + "\n");
                sb.append("系统：" + jsonObject.get("sysName") + "\n");
                sb.append("站点：" +  jsonObject.get("stationName") + "\n");
                sb.append("告警内容：" + jsonObject.get("alertInfo") + "\n");
                sb.append("时间：" + jsonObject.get("alertTime")  + "\n");
                sb.append("------------------------------------\n");
            }
        }else{//审批
            if("0".equals(data1.getString("totalCount"))){
                return;
            }
            data = data1.getJSONArray("data");
            sb.append("您有" + data1.get("totalCount") + "条审批，请查收\n");
            SummaryText = "您有" + data1.get("totalCount") + "条审批，请查收\n";
            intent.putExtra("notify","examine");
            title = "审批通知";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("审批：" + jsonObject.get("alarmContent") + "\n");
                sb.append("时间：" +  jsonObject.get("createTime") + "\n");
                sb.append("------------------------------------\n");
            }
        }

        // 获取RemoteViews对象，设置自定义布局
        @SuppressLint("RemoteViewLayout")
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.custom_notification);

        builder.setContentTitle("横幅通知");
        builder.setContentText("请在设置通知管理中开启消息横幅提醒权限");
        builder.setDefaults(NotificationCompat.DEFAULT_ALL);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setCustomContentView(remoteViews);
//        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.notification));
//        Intent intent = new Intent(this,ImageActivity.class);
//        PendingIntent pIntent = PendingIntent.getActivity(this,1,intent,0);
//        builder.setContentIntent(pIntent);
//        //这句是重点
//        builder.setFullScreenIntent(pIntent,true);
        builder.setAutoCancel(true);
        Notification notification = builder.build();
        manager.notify(1,notification);
    }
    @SuppressLint("WrongConstant")
    public void notificationALarm(JSONObject data1,int type) throws JSONException {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = null;
        String channelId = "com.message.notify"+type;
        String channelName = "notification";
        //判断api版本大于等于26
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_LOW);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(this, channelId);
        } else {
            builder = new NotificationCompat.Builder(this);
            builder.setChannelId(channelId);
        }
        JSONArray data;
        StringBuffer sb = new StringBuffer();

        String title;
        String SummaryText;
        Intent intent = new Intent(this, MainActivity.class);

        if(type == 0){//告警
            if("0".equals(data1.getString("total"))){
                return;
            }
            data = data1.getJSONArray("list");
            sb.append("您有" + data1.get("total") + "条告警，请查收\n");
            SummaryText = "您有" + data1.get("total") + "条告警，请查收\n";
            intent.putExtra("notify","warn");
            title = "告警通知";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("系统：" + jsonObject.get("sysName") + "\n");
                sb.append("站点：" +  jsonObject.get("stationName") + "\n");
                sb.append("告警内容：" + jsonObject.get("alertInfo") + "\n");
                sb.append("异常时间：" + jsonObject.get("alertTime")  + "\n");
                sb.append("------------------------------------\n");
            }
        }else{//审批
            if("0".equals(data1.getString("totalCount"))){
                return;
            }
            data = data1.getJSONArray("data");
            sb.append("您有" + data1.get("totalCount") + "条审批，请查收\n");
            SummaryText = "您有" + data1.get("totalCount") + "条审批，请查收\n";
            intent.putExtra("notify","examine");
            title = "审批通知";
            for(int i = 0;i<data.length();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                sb.append("审批：" + jsonObject.get("alarmContent") + "\n");
                sb.append("时间：" +  jsonObject.get("createTime") + "\n");
                sb.append("------------------------------------\n");
            }
        }


        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        bigTextStyle.setBigContentTitle(title)
                .setSummaryText(SummaryText)
                .bigText(sb.toString());

        builder.setContentTitle(title)//设置消息通知标题
                .setContentText(sb.toString())//设置消息通知内容
                .setStyle(bigTextStyle)
                .setWhen(System.currentTimeMillis())//设置消息通知发送时间
                .setSmallIcon(R.mipmap.app_icon)//设置小童通知状态栏图标
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.app_icon))//设置消息通知下拉图标
                .setCategory(NotificationCompat.CATEGORY_MESSAGE) // 通知类别，"勿扰模式"时系统会决定要不要显示你的通知
                .setVisibility(NotificationCompat.VISIBILITY_PRIVATE) // 屏幕可见性，锁屏时，显示icon和标题，内容隐藏
                .setPriority(NotificationCompat.PRIORITY_MAX);//设置消息优先级

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        builder.setContentIntent(pendingIntent);

        //点击消息通知后删除的两种实现方法
        //第一种
        builder.setAutoCancel(true);
        //第二种
        int notificationId = 1;
//        manager.cancel(notificationId);

        //设置消息通知的提醒效果
        builder.setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luan.ogg")))//设置消息声音
                .setVibrate(new long[]{0, 1000, 1000, 1000})//设置消息震动，需要加入android.permission.VIBRATE权限
                .setLights(Color.GREEN, 1000, 1000)//设置消息提醒灯
                .setDefaults(NotificationCompat.VISIBILITY_PUBLIC);//设置默认效果

        //设置悬挂弹出
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        builder.setFullScreenIntent(pendingIntent, true);

        Notification notification = builder.build();
        manager.notify(notificationId, notification);
    }

    public void getMsg() {
        HttpUtility.get("SERVER_URL","", new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);

            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }

        });
    }

    public void initAuthorization(View view,String username,String password) {
        StringBuffer dataBuffer = new StringBuffer();
        try {
            dataBuffer.append(URLEncoder.encode("username", "UTF-8"));
            dataBuffer.append("=");
            dataBuffer.append(URLEncoder.encode(username, "UTF-8"));

            dataBuffer.append("&");

            dataBuffer.append(URLEncoder.encode("password", "UTF-8"));
            dataBuffer.append("=");
            dataBuffer.append(URLEncoder.encode(password, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String params = dataBuffer.toString();;
        HttpUtility.post("http://106.37.212.101:8081/api/v1/login", params, new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    String token = jsonObject.getString("token");
                    SharedPreferencesManager instance = SharedPreferencesManager.getInstance(MainActivity.this);
                    SharedPreferences.Editor edit = instance.getSharedPreferences().edit();

                    edit.putString("auth",token);
                    edit.apply();

                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }

                //Toast.makeText(this, "Toast消息提醒", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }
        });
    }

    public void getauth_warn(View view) {
        SharedPreferencesManager instance = SharedPreferencesManager.getInstance(MainActivity.this);
        String token = instance.getSharedPreferences().getString("auth", null);
        Log.e("TAG", token);
        //告警
        HttpUtility.get("http://106.37.212.101:8081/api/v1/alarm/alert/newest?span=150&showInfo=2&alertSignal=1",token, new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    JSONObject data1 = jsonObject.getJSONObject("data");
                    notificationALarm(data1,0);

                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }

        });


    }

    public void getauth_examine(View view) {
        SharedPreferencesManager instance = SharedPreferencesManager.getInstance(MainActivity.this);
        String token = instance.getSharedPreferences().getString("auth", null);
        Log.e("TAG", token);

        //审批
        HttpUtility.get("http://106.37.212.101:8081/api/v1/alarm/apply/pending",token, new HttpUtility.OnRequestCallBack() {

            @Override
            public void onSuccess(String json) {
                Log.d("TAG", json);

                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(json);
                    JSONObject data1 = jsonObject.getJSONObject("data");
                    notificationALarm(data1,1);


                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onError(String errorMsg) {
                Log.e("TAG", errorMsg);
            }

        });

    }


}